<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="author" content="jeessy2" />
    <title>IPV6链接复制</title>
    <link
      class="theme"
      rel="stylesheet"
      type="text/css"
      href="./static/common.css"
    />
    <link rel="stylesheet" href="./static/bootstrap.min.css" />
    <link rel="stylesheet" href="./static/theme-button.css" />
    <script src="./static/constant.js"></script>
    <script src="./static/utils.js"></script>
    <script src="./static/i18n.js"></script>
  </head>

  <body>
    <header>
      <div class="navbar navbar-dark bg-dark shadow-sm">
        <div class="button-container container d-flex justify-content-between">
          <a
            target="blank"
            href="https://github.com/jeessy2/ddns-go"
            class="navbar-brand d-flex align-items-center"
          >
            <strong>IPV6链接复制</strong>
          </a>
          <span class="badge badge-secondary">{{.Version}}</span>
        </div>
      </div>
    </header>

    <main role="main">
      <div id="mask" style="visibility: hidden"></div>
      <div class="row">
        <div class="col-md-6 offset-md-3">
          <form id="formDnsConf">
            <div class="portlet">
              <h5 class="portlet__head">点击下方按钮复制</h5>
              <div class="portlet__body">
                <div class="form-group row">
                  <div class="col-sm-10">
                    <select
                      class="form-control"
                      id="Ipv6NetInterface"
                      name="Ipv6NetInterface"
                      data-visible="netInterface"
                    >
                      {{range .Ipv6}}
                        {{range .Address}}
                      <option value="{{.}}">
                        {{.}}
                      </option>
                        {{end}}
                      {{end}}
                    </select>
                  </div>
                   <div class="col-sm-10 text-center justify-content-center">
                        <input
                                class="form-control form"
                                id="copyIpv6Url"
                                name="copyIpv6Url"
                                style="margin-top: 10px"
                                value="http://[{{(index (index .Ipv6 0).Address 0)}}]"
                                readonly
                        />
                        <div class="col-sm-10" style="justify-content: space-around;display: flex;">
                            <span
                                    class="btn btn-warning copy-1_btn"
                                    style="margin-bottom: 16px;margin-top: 1px"
                                    id="copy-1_btn"
                            >
                                复制IPV6
                            </span>
                            <span
                                    class="btn btn-success copy-11_btn"
                                    style="margin-bottom: 16px;margin-top: 1px"
                                    id="copy-11_btn"
                            >
                                跳转
                            </span>
                        </div>
                    </div>
                   <div class="col-sm-10 text-center justify-content-center">
                        <input
                                type="text"
                                class="form-control form"
                                id="Ipv6Emby"
                                name="Ipv6Emby"
                                aria-describedby="Ipv6CmdHelp"
                                value="http://[{{(index (index .Ipv6 0).Address 0)}}]:8096"
                                readonly
                        />
                        <div class="col-sm-10" style="justify-content: space-around;display: flex;">
                            <span
                                    class="btn btn-warning copy-2_btn"
                                    style="margin-bottom: 16px;margin-top: 2px"
                                    id="copy-2_btn"
                            >
                                复制EMBY
                            </span>
                            <span
                                    class="btn btn-success copy-22_btn"
                                    style="margin-bottom: 16px;margin-top: 2px"
                                    id="copy-22_btn"
                            >
                                跳转
                            </span>
                        </div>
                    </div>
                   <div class="col-sm-10 text-center justify-content-center">
                        <input
                                type="text"
                                class="form-control form"
                                id="Ipv6Tos"
                                name="Ipv6Tos"
                                value="http://[{{(index (index .Ipv6 0).Address 0)}}]:8181"
                                readonly
                        />
                        <div class="col-sm-10" style="justify-content: space-around;display: flex;">
                            <span
                                    class="btn btn-warning copy-3_btn"
                                    style="margin-bottom: 10px;margin-top: 2px"
                                    id="copy-3_btn"
                            >
                                复制TOS
                            </span>
                            <span
                                    class="btn btn-success copy-33_btn"
                                    style="margin-bottom: 10px;margin-top: 2px"
                                    id="copy-33_btn"
                            >
                                跳转
                            </span>
                        </div>
                    </div>
                   <div class="col-sm-10" id="copyMessage" style="text-align: center;background-color: #dee2e6;visibility: hidden">
                       <span id="copyMessageText" style="padding: 0;">已复制</span>
                    </div>
                </div>
              </div>
            </div>
          </form>
        </div>
        <div
          class="logs-panel col-md-6 offset-md-3"
          style="visibility: hidden"
          id="logs-panel"
        >
          <textarea class="logs form-control" id="logs" readonly></textarea>
          <button
            data-i18n="Clear"
            type="button"
            class="btn btn-danger btn-sm"
            id="clearLogBtn"
          >
            Clear
          </button>
          <button
            data-i18n="OK"
            type="button"
            class="btn btn-primary btn-sm"
            style="float: right"
            id="closeLogBtn"
          >
            OK
          </button>
        </div>
      </div>
    </main>

  </body>

  <!-- 全局变量 -->
  <script>
    let configIndex = -1;
    let dnsConf = [];
    const globalConf = {
      // NotAllowWanAccess: document.getElementById("NotAllowWanAccess").checked,
      // Username: document.getElementById("Username").value,
      // Password: document.getElementById("Password").value,
      // WebhookURL: document.getElementById("WebhookURL").value,
      // WebhookRequestBody: document.getElementById("WebhookRequestBody").value,
      // WebhookHeaders: document.getElementById("WebhookHeaders").value,
    };
    const defaultDnsConf = {
      DnsID: "",
      DnsName: "alidns",
      DnsSecret: "",
      Ipv4Cmd: "",
      Ipv4Domains: "",
      Ipv4Enable: true,
      Ipv4GetType: "url",
      Ipv4NetInterface: "",
      Ipv4Url: i18n({
        "en": "https://api.ipify.org, https://ddns.oray.com/checkip, https://ip.3322.net, https://4.ipw.cn",
        "zh-cn": "https://myip.ipip.net, https://ddns.oray.com/checkip, https://ip.3322.net, https://4.ipw.cn",
      }),
      Ipv6Cmd: "",
      Ipv6Domains: "",
      Ipv6Enable: true,
      Ipv6GetType: "netInterface",
      // Ipv6NetInterface: "",
      Ipv6Reg: "",
      Ipv6Url: i18n({
        "en": "https://api64.ipify.org, https://speed.neu6.edu.cn/getIP.php, https://v6.ident.me, https://6.ipw.cn",
        "zh-cn": "https://speed.neu6.edu.cn/getIP.php, https://v6.ident.me, https://6.ipw.cn",
      }),
      TTL: "",
    };
  </script>

  <!-- 表单相关 -->

  <script>
      function copyToClipboard(text) {
          var textarea = document.createElement('textarea');
          textarea.style.position = 'fixed';
          textarea.style.opacity = 0;
          textarea.value = text;
          document.body.appendChild(textarea);
          textarea.select();
          document.execCommand('copy');
          document.body.removeChild(textarea);
      }

      function copyToClipboardNew(text) {
          navigator.clipboard.writeText(text)
              .then(function() {
                  console.log('Text copied to clipboard');
              })
              .catch(function(err) {
                  console.error('Failed to copy text: ', err);
              });
      }

      document.getElementById("copy-1_btn").addEventListener('click', e => {
          e.preventDefault();
          var copyVal = document.getElementById("copyIpv6Url").value;
          try {
              copyToClipboardNew(copyVal);
          } catch(e) {
              copyToClipboard(copyVal);
          }
          document.getElementById("copyMessage").style.visibility = "";
          document.getElementById("copyMessageText").innerHTML="已复制IPV6";
      });

      document.getElementById("copy-11_btn").addEventListener('click', e => {
          e.preventDefault();
          var copyVal = document.getElementById("copyIpv6Url").value;
          window.open(copyVal,"_blank");
      });

      document.getElementById("copy-2_btn").addEventListener('click', e => {
          e.preventDefault();
          var copyVal = document.getElementById("Ipv6Emby").value;
          try {
              copyToClipboardNew(copyVal);
          } catch(e) {
              copyToClipboard(copyVal);
          }
          document.getElementById("copyMessage").style.visibility = "";
          document.getElementById("copyMessageText").innerHTML="已复制EMBY";
      });

      document.getElementById("copy-22_btn").addEventListener('click', e => {
          e.preventDefault();
          var copyVal = document.getElementById("Ipv6Emby").value;
          window.open(copyVal,"_blank");
      });

      document.getElementById("copy-3_btn").addEventListener('click', e => {
          e.preventDefault();
          var copyVal = document.getElementById("Ipv6Tos").value;
          try {
              copyToClipboardNew(copyVal);
          } catch(e) {
              copyToClipboard(copyVal);
          }
          document.getElementById("copyMessage").style.visibility = "";
          document.getElementById("copyMessageText").innerHTML="已复制TOS";
      });

      document.getElementById("copy-33_btn").addEventListener('click', e => {
          e.preventDefault();
          var copyVal = document.getElementById("Ipv6Tos").value;
          window.open(copyVal,"_blank");
      });

      // 获取select元素
      var selectElement = document.getElementById('Ipv6NetInterface');
      // 为select元素添加'change'事件监听器
      selectElement.addEventListener('change', function(event) {
          // 获取选中的option的值
          var selectedValue = selectElement.options[selectElement.selectedIndex].value;
          // 在这里编写当选择改变时需要执行的代码
          document.getElementById("Ipv6Emby").value="http://["+selectedValue+"]:8096";
          document.getElementById("Ipv6Tos").value="http://["+selectedValue+"]:8181";
          document.getElementById("copyIpv6Url").value="http://["+selectedValue+"]";
      });

  </script>

  <!-- 配置项 -->
  <script>
    // 把dnsConf中的值填充到表单中
    /*function showConf(idx) {
      const conf = dnsConf[idx] ?? {};
      for (const name in conf) {
        const $e = document.querySelector(`[name=${name}]`);
        // 判断对应input的类型
        switch ($e.getAttribute("type")) {
          case "checkbox":
            $e.checked = conf[name];
            break;
          case "radio":
            document.querySelector(`[name=${name}][value=${conf[name]}]`).click();
            break;
          default:
            //特殊处理select类型，要保证option存在，否则取第一个option
            if ($e.tagName === "SELECT" &&
              $e.querySelector(`option[value="${conf[name]}"]`) === null) {
              $e.value = $e.querySelector("option")?.value;
              conf[name] = $e.value||"";
            }
            // 如果是其它类型的input或者不是input（如textarea），都使用value赋值
            $e.value = conf[name];
            break;
        }
      }
    }*/

    // 从json中重新加载配置
    /*function reloadConf(jsonConf) {
      try {
        dnsConf = JSON.parse(jsonConf);
        if (dnsConf.length === 0) {
          console.warn("dnsConf is empty, add defaultDnsConf");
          dnsConf.push({...defaultDnsConf});
        }
      } catch (e) {
        alert("error: " + e.toString());
        return;
      }
      const $select = document.getElementById("index");
      $select.innerHTML = "";
      for (let i = 0; i < dnsConf.length; i++) {
        const $option = html2Element(`
          <option id="index_${i}" value="${i}">
            ${i + 1} - ${dnsConf[i].DnsName}
          </option>
        `);
        $select.appendChild($option);
      }
      // 负数表示倒数第几个
      if (configIndex < 0) {
        configIndex += dnsConf.length;
      } else {
        configIndex = Math.min(configIndex, dnsConf.length - 1);
      }
      $select.value = configIndex;
      showConf(configIndex);
    }*/

    // 新增配置按钮被点击
    /*document.getElementById("addBtn").addEventListener('click', e => {
      e.preventDefault();
      configIndex = dnsConf.length;
      dnsConf[configIndex] = {...defaultDnsConf};
      // 创建新的option
      const $index = document.getElementById("index");
      const $option = html2Element(`
        <option id="index_${configIndex}" value="${configIndex}">
          ${configIndex + 1} - ${dnsConf[configIndex].DnsName}
        </option>
      `);
      $index.appendChild($option);
      $index.value = configIndex;
      showConf(configIndex);
    });*/

    // 删除配置按钮被点击
    /*document.getElementById("delBtn").addEventListener('click', e => {
      e.preventDefault();
      const $index = document.getElementById("index");
      $index.options[configIndex].disabled = true;
      $index.options[configIndex].text = configIndex + 1 + " - Deleted";
      dnsConf[configIndex] = null;
      while (dnsConf[configIndex] === null && configIndex >= 0) {
        configIndex--;
      }
      if (configIndex >= 0) {
        $index.value = configIndex;
        showConf(configIndex);
      } else {
        document.getElementById("addBtn").click();
      }
    });*/

    // 保存配置按钮被点击
    /*document.querySelectorAll(".submit_btn").forEach($el => {
      $el.addEventListener('click', async e => {
        e.preventDefault();
        // 如果没有idLabel，删除DnsID
        if (!DNS_PROVIDERS[dnsConf[configIndex].DnsName].idLabel) {
          dnsConf[configIndex].DnsID = "";
        }
        try {
          const resp = await request.post("./save", {
            ...globalConf,
            DnsConf: dnsConf
          });
          if (resp.result !== "ok") {
            showMessage({
              content: resp.result,
              type: "error",
              duration: 5000,
            });
          } else {
            showMessage({
              content: i18n({
                "en": "Successfully saved",
                "zh-cn": "保存成功",
              }),
              type: "success",
              duration: 1500,
            });
            reloadConf(resp.dnsConf);
          }
        } catch (err) {
          alert(`${err.toString()}`);
        }
      });
    });*/

    // 切换配置项
    /*document.getElementById("index").addEventListener('change', e => {
      configIndex = parseInt(e.target.value);
      showConf(configIndex);
    });*/

    // 初始化dnsConf
    // reloadConf("{{.DnsConf}}");
  </script>

  <!-- 日志相关函数和日志初始化 -->
  <script>
    // 获取日志
    const getLogs = async (loop = false) => {
      let logsList = [];
      try {
        const resp = await request.get("./logs");
        // 如果不是数组，说明返回的是错误信息
        if (!Array.isArray(resp)) {
          throw new Error(resp);
        }
        logsList = resp;
      } catch (err) {
        showMessage({
          content: err.toString(),
          type: "error",
          duration: 5000,
        });
        return;
      } finally {
        if (loop) {
          setTimeout(getLogs, 5 * 1000, true);
        }
      }
      const $logs = document.getElementById("logs");
      // 判断滚动条是否在底部
      const isBottom = $logs.scrollHeight - $logs.scrollTop - $logs.clientHeight < 10;
      $logs.value = logsList.join("");
      // 如果滚动条原先在底部，滚动到底部
      if (isBottom) {
        $logs.scrollTop = $logs.scrollHeight;
      }
      const oldLogItem = localStorage.getItem("logItem") || "";
      localStorage.setItem(
        "logItem",
        logsList[logsList.length - 1] || ""
      );
      // 计算日志更新部分
      const newLogsList = logsList.slice(
        // 如果oldLogItem出现多次，使用indexOf会得到第一次出现的位置导致一直判定为有新日志，所以这里使用lastIndexOf
        logsList.lastIndexOf(oldLogItem) + 1
      );
      // 如果日志面板可见或者没有新增日志，则不显示
      if (
        !newLogsList.length ||
        document.getElementById("logs-panel").style.visibility !== "hidden"
      ) {
        return;
      }
      document.getElementById("logsBtn").classList.add("unread");
      // 如果新增日志行数小于等于3，则message显示新增日志，否则显示最后2行并提示剩余行数
      if (newLogsList.length <= 3) {
        for (const line of newLogsList) {
          showMessage({
            type: "info",
            content: line,
          });
          await delay(800);
        }
      } else {
        showMessage({
          type: "info",
          content: i18n({
            "en": `Please check the previous ${newLogsList.length - 2} logs by yourself`,
            "zh-cn": `前${newLogsList.length - 2}条日志请自行查看`,
          })
        });
        for (const line of newLogsList.slice(-2)) {
          showMessage({
            type: "info",
            content: line,
          });
          await delay(800);
        }
      }
    }

    // 清空日志
    /*document.getElementById("clearLogBtn").addEventListener('click', async e => {
      e.preventDefault();
      try {
        await request.get("./clearLog");
        getLogs();
      } catch (err) {
        showMessage({
          content: err.toString(),
          type: "error",
          duration: 5000,
        });
      }
    });*/

    // 显示/隐藏日志面板
    /*document.querySelectorAll('#logsBtn, #closeLogBtn, #mask').forEach($el => {
      $el.addEventListener('click', () => {
        // 取消未读标记
        document.getElementById("logsBtn").classList.remove("unread");
        if (document.getElementById("logs-panel").style.visibility === "hidden") {
          document.getElementById("logs-panel").style.visibility = "";
          document.getElementById("mask").style.visibility = "";
        } else {
          document.getElementById("logs-panel").style.visibility = "hidden";
          document.getElementById("mask").style.visibility = "hidden";
        }
      });
    });*/

    // 页面加载完成后定时获取日志
    /*document.addEventListener('DOMContentLoaded', () => getLogs(true));*/
  </script>

  <!-- 主题色相关的函数和初始化 -->
  <!--<script src="./static/theme.js"></script>-->

</html>
